/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.network;

import java.security.*;

import org.latestbit.smartobjects.ISmartBus;
import org.latestbit.smartobjects.encrypters.*;

public class StdHandshakeManagerFactory implements IHandshakeManagerFactory {

	protected IConnectionAuthenticator authenticator = new StdNullConnectionAuthenticator();
	protected ISmartBus bus;
	protected IAsymmetricDataEncrypter encrypter;
	private KeyPair keyPair;
	private IHandshakeManagerListener handshakeManagerListener;

	public StdHandshakeManagerFactory(ISmartBus bus) {
		this.bus = bus;
		// initEncrypter();
	}
	
	@Override
	public ISmartBus getBus() {
		return this.bus;
	}
	
	protected void initEncrypter() {
		try {
			encrypter = this.bus.getDataEncrypterFactory().createAsymmetricEncrypter();
			this.keyPair = encrypter.generateKeyPair();
			encrypter.initCipher( keyPair.getPrivate() );
		}
		catch(GeneralSecurityException ex) {
			ex.printStackTrace();
		}
	}
	
	@Override
	public KeyPair getKeyPair() {
		return this.keyPair;
	}

	@Override
	public IHandshakeManager createHandshakeManager( IConnection connection ) {
		return new StdHandshakeManager( this, connection );
	}

	@Override
	public IConnectionAuthenticator getConnectionAuthenticator() {		
		return this.authenticator;
	}

	@Override
	public void setConnectionAuthenticator( IConnectionAuthenticator authenticator ) {
		this.authenticator  = authenticator;
		if(this.authenticator == null) {
			this.authenticator = new StdNullConnectionAuthenticator();
		}
	}

	@Override
	public IAsymmetricDataEncrypter getAsymmetricDataEncrypter() {
		synchronized(this) {
			if(this.encrypter == null)
				initEncrypter();
		}
		
		return this.encrypter;
	}

	@Override
	public IHandshakeManagerListener getHandshakeManagerListener() {
		return handshakeManagerListener;
	}

	@Override
	public void setHandshakeManagerListener(IHandshakeManagerListener listener) {
		handshakeManagerListener = listener;
	}
}
